package com.luhai.shipmentscheck.activity;

import android.content.Context;
import android.content.Intent;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luhai.shipmentscheck.R;
import com.luhai.shipmentscheck.config.Constants;
import com.luhai.shipmentscheck.entity.CheckAction;
import com.luhai.shipmentscheck.entity.Info;
import com.luhai.shipmentscheck.manager.MySensorManager;
import com.luhai.shipmentscheck.manager.QRCodeManager;
import com.luhai.shipmentscheck.util.OkHttpUtils;
import com.luhai.shipmentscheck.util.ShakeUtil;
import com.luhai.shipmentscheck.util.ToastUtil;
import com.luhai.shipmentscheck.widget.TextureCameraPreview;


import android.graphics.Color;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Type;


public class MainActivity extends BaseActivity implements QRCodeManager.OnQrCodeRecognizeListener, OkHttpUtils.OkHttpCallBackLinener, Animation.AnimationListener, MySensorManager.OnSensorChangeListener {


    private Animation up_down, down_up, left_right, small_big, big_small;

    /**
     * 当前正在执行动画的行
     */
    private int line_animing = 0;

    private String current_cl_id;

    private TextureCameraPreview tcp_preview;

    private ImageView iv_scan_line, iv_no, iv_yes;

    private LinearLayout ll_all_count, ll_order_number, ll_part_number, ll_remind, ll_info_show, ll_left, ll_light;

    private TextView tv_check_number, tv_part_number, tv_part_number_pass, tv_order_number, tv_order_number_pass, tv_all_count, tv_all_count_pass, tv_remind;

    private boolean isPass;

    /**
     * 当前料号、订单号、总数量是否pass的状态封装类
     */
    private CheckAction checkAction;

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_yes:
                QRCodeManager.getSingleTon().startQRCodeRecognize();
                controlResultAnimation(false);
                controlScanAnimation(true);
                break;

            case R.id.iv_no:

                if (isPass) {
                    QRCodeManager.getSingleTon().startQRCodeRecognize();
                    controlResultAnimation(false);
                    controlScanAnimation(true);
                } else {
                    finish();
                }
                break;
            case R.id.ll_left:
                finish();
                break;
            case R.id.ll_light:
                if(tcp_preview.isFlashLightOpen()){
                    tcp_preview.closeFlashLight();
                }else{
                    tcp_preview.openFlashLight();
                }
                break;
        }
    }

    @Override
    protected void init() {

        Intent intent = getIntent();
        current_cl_id = intent.getStringExtra("cl_id");
        MySensorManager.getSingleTon().init(this, this);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(View view) {
        tcp_preview = findViewById(R.id.tcp_preview);
        tcp_preview.setOnStartCameraListener(QRCodeManager.getSingleTon());
        tv_check_number = findViewById(R.id.tv_check_number);
        tv_check_number.setText(current_cl_id);
        tv_part_number = findViewById(R.id.tv_part_number);
        tv_part_number_pass = findViewById(R.id.tv_part_number_pass);
        tv_order_number = findViewById(R.id.tv_order_number);
        tv_order_number_pass = findViewById(R.id.tv_order_number_pass);
        tv_all_count = findViewById(R.id.tv_all_count);
        tv_all_count_pass = findViewById(R.id.tv_all_count_pass);
        tv_remind = findViewById(R.id.tv_remind);
        iv_scan_line = findViewById(R.id.iv_scan_line);
        ll_all_count = findViewById(R.id.ll_all_count);
        ll_order_number = findViewById(R.id.ll_order_number);
        ll_part_number = findViewById(R.id.ll_part_number);
        ll_light = findViewById(R.id.ll_light);
        ll_left = findViewById(R.id.ll_left);
        ll_info_show = findViewById(R.id.ll_info_show);
        ll_remind = findViewById(R.id.ll_remind);
        iv_yes = findViewById(R.id.iv_yes);
        iv_no = findViewById(R.id.iv_no);

        up_down = AnimationUtils.loadAnimation(this, R.anim.in_from_down);
        down_up = AnimationUtils.loadAnimation(this, R.anim.out_to_up);
        left_right = AnimationUtils.loadAnimation(this, R.anim.left_right);
        small_big = AnimationUtils.loadAnimation(this, R.anim.small_big);
        big_small = AnimationUtils.loadAnimation(this, R.anim.big_small);
    }

    @Override
    public void setListener() {
        left_right.setAnimationListener(this);
        small_big.setAnimationListener(this);
        big_small.setAnimationListener(this);
        iv_yes.setOnClickListener(this);
        iv_no.setOnClickListener(this);
        ll_left.setOnClickListener(this);
        ll_light.setOnClickListener(this);
    }

    @Override
    public void doBusiness(Context mContext) {

        //OkHttpUtils.getInstance().setTimeOut(5,5,5);
        QRCodeManager.getSingleTon().init(this);
        QRCodeManager.getSingleTon().startQRCodeRecognize();
        controlScanAnimation(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MySensorManager.getSingleTon().destroy();
        QRCodeManager.getSingleTon().stopQRCodeRecognize();
    }

    @Override
    public void onResult(String result) {

        // ToastUtil.showToast(result);
        ShakeUtil.shake(this);
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        controlScanAnimation(false);
        if(result!=null && result.matches(regex)) {
            Log.i(TAG, "IP：" + Constants.URL_GET_SHIPMENTS_CHECK_INFO + "?rid=" + result + "&cl_id=" + current_cl_id);
            OkHttpUtils.getInstance().doGet(Constants.URL_GET_SHIPMENTS_CHECK_INFO + "?rid=" + result + "&cl_id=" + current_cl_id, this);
        }else{
            ToastUtil.showToast("请扫码专属二维码！");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            QRCodeManager.getSingleTon().startQRCodeRecognize();
                        }
                    },2000);
                }
            });
        }
    }

    boolean isFirst = true;

    @Override
    protected void onResume() {
        super.onResume();
        if (tcp_preview != null && !isFirst) {
            tcp_preview.restartPreview();
            isFirst = false;
        }
    }

    @Override
    public void onError() {

    }

    @Override
    public void failure(Exception e) {

        ToastUtil.showToast("网络请求异常，已重新开启扫描！");
        QRCodeManager.getSingleTon().startQRCodeRecognize();
        controlScanAnimation(true);
    }

    @Override
    public void success(String json) {

        Log.i(TAG, "获取到的JSON：" + json);
        //将json格式字符串转换为List对象
        Type type = new TypeToken<Info>() {
        }.getType();
        Info info = new Gson().fromJson(json, type);
        Log.i(TAG, "转换成的INFO对象为：" + info.toString());
        refresh(info);

    }

    public void controlScanAnimation(boolean isStart) {

        if (isStart) {
            iv_scan_line.startAnimation(up_down);
            up_down.setAnimationListener(this);
            down_up.setAnimationListener(this);
        } else {
            iv_scan_line.clearAnimation();
            up_down.setAnimationListener(null);
            down_up.setAnimationListener(null);
        }
    }

    public void controlResultAnimation(boolean isShow) {

        if (isShow) {
            ll_part_number.setVisibility(View.VISIBLE);
            ll_part_number.startAnimation(left_right);
            line_animing = 1;
        } else {
            ll_info_show.startAnimation(big_small);
        }
    }

    public void refresh(Info info) {

        tv_part_number.setText(info.in_mtrl);
        tv_order_number.setText(info.cust_so);
        tv_all_count.setText((Float.valueOf(info.rid_qty).intValue() + ""));
        tv_all_count_pass.setText(info.result);
        tv_order_number_pass.setText(info.result);
        tv_part_number_pass.setText(info.result);
        if ("PASS".equals(info.result)) {
            isPass = true;
            tv_remind.setText("OQC核对通过，请确认！");
            tv_all_count_pass.setTextColor(Color.GREEN);
            tv_order_number_pass.setTextColor(Color.GREEN);
            tv_part_number_pass.setTextColor(Color.GREEN);
        } else {
            isPass = false;
            tv_remind.setText("是否继续下一箱扫描？");
            tv_all_count_pass.setTextColor(Color.RED);
            tv_order_number_pass.setTextColor(Color.RED);
            tv_part_number_pass.setTextColor(Color.RED);
        }
        controlResultAnimation(true);
    }

    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {

        if (animation == up_down) {
            down_up.start();
        } else if (animation == down_up) {
            up_down.start();
        } else if (animation == left_right) {
            if (line_animing == 1) {
                ll_part_number.clearAnimation();
                ll_order_number.setVisibility(View.VISIBLE);
                ll_order_number.startAnimation(left_right);
                line_animing = 2;
            } else if (line_animing == 2) {
                ll_order_number.clearAnimation();
                ll_all_count.setVisibility(View.VISIBLE);
                ll_all_count.startAnimation(left_right);
                line_animing = 3;
            } else if (line_animing == 3) {
                ll_all_count.clearAnimation();
                ll_remind.setVisibility(View.VISIBLE);
                ll_remind.startAnimation(small_big);
                line_animing = 4;
            }
        } else if (animation == big_small) {
            ll_part_number.setVisibility(View.GONE);
            ll_remind.setVisibility(View.GONE);
            ll_all_count.setVisibility(View.GONE);
            ll_order_number.setVisibility(View.GONE);
        }
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }

    @Override
    public void onLightChangeListener(float light) {

        if (light <= 10) {
            ll_light.setVisibility(View.VISIBLE);
        } else {
            if (!tcp_preview.isFlashLightOpen()) {
                ll_light.setVisibility(View.GONE);
            }
        }
    }
}
